package org.montoroTurismo.beans;

import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.montoroTurismo.dao.AccesoBD;
import org.primefaces.context.RequestContext;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ajdiaz
 */
public class LoginBean {

    private String username;
    private String password;
    private final FacesContext faceContext;
    private final HttpServletRequest httpServletRequest;

    public LoginBean() {
        faceContext = FacesContext.getCurrentInstance();
        httpServletRequest = (HttpServletRequest) faceContext.getExternalContext().getRequest();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String login() {
        FacesMessage msg = null;
        String succes = "";
        boolean result = false;
        RequestContext context = RequestContext.getCurrentInstance();  
        result = validarLogin();

        if (result == true) {
           
            httpServletRequest.getSession().setAttribute("sessionUsuario", username);
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
            succes = "succes";
        } else {
            
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
        }

        FacesContext.getCurrentInstance().addMessage(null, msg);
         context.addCallbackParam("loggedIn", result);  
        return succes;
    }

    private boolean validarLogin() {


        boolean result = false;
        ResultSet rs;
        String query = "Select usuario, password from usuario where usuario='" + username + "' AND password='" + password + "'";
        try {
            AccesoBD conection = new AccesoBD();
            rs = conection.executeQueryDataBase(query);
            while (rs.next()) {
                if (rs.getRow() > 0) {
                    System.out.println("DATOS RESULSET:  " + rs.getString("usuario"));
                    System.out.println("DATOS RESULSET:  " + rs.getString("password"));
                    result = true;

                }
            }

            conection.close();
        } catch (Exception ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        return result;

    }
}
